package com.qiall.boot.userservice.Impl.user;

import com.alibaba.fastjson.JSON;
import com.qiall.boot.cache.ability.service.CacheService;
import com.qiall.boot.userservice.Impl.login.DataBuildUtil;
import com.qiall.boot.userservice.Impl.user.activity.UserConvert;
import com.qiall.boot.userservice.data.entity.UserInfo;
import com.qiall.boot.userservice.data.entity.UserQueryBean;
import com.qiall.boot.userservice.data.mapper.UserMapper;
import com.qiall.common.entity.PageResponse;
import com.qiall.common.exception.BusinessException;
import com.qiall.common.exception.BusinessResult;
import com.qiall.common.exception.ResultCode;
import com.qiall.common.request.BaseRequest;
import com.qiall.common.request.BaseResponse;
import com.qiall.common.request.GetByIdRequest;
import com.qiall.user.ability.entity.*;
import com.qiall.user.ability.service.user.UserService;
import com.qiall.boot.userservice.Impl.user.activity.CreateUserPreCheckActivity;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.compress.utils.Lists;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
@DubboService
public class UserServiceImpl implements UserService {

    @DubboReference
    private CacheService cacheService;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserConvert userConvert;

    @Autowired
    private CreateUserPreCheckActivity createUserPreCheckActivity;

    private static String ADMIN_NAME = "admin";

    @Value("${user.info.redis.expire}")
    private Integer expire;

    @Override
    public BusinessResult<UserInfoDTO> getUserInfoByAuthCode(BaseRequest authDTO) {
        String accessToken = authDTO.getAccessToken();
        String useInfoString = cacheService.getValue(DataBuildUtil.buildAccessToken(accessToken)).getBody();
        if (StringUtils.isBlank(useInfoString)) {
            throw new BusinessException(ResultCode.USER_NOT_LOGIN);
        }
        // 重置redis key 超时时间
        cacheService.expire(DataBuildUtil.buildAccessToken(accessToken), expire);
        UserInfo userInfo = JSON.parseObject(useInfoString, UserInfo.class);
        UserInfoDTO userInfoDTO = userConvert.transToUserInfoDTO(userInfo);
        return BusinessResult.success(userInfoDTO);
    }

    @Override
    public BusinessResult<BaseResponse> createUserInfo(CreateUserDTO userInfoDTO) {
        UserInfoDTO userInfoResp = new UserInfoDTO();
        // 前置校验
        createUserPreCheckActivity.handler(userInfoDTO, userInfoResp);
        // 转换
        UserInfo userInfo = userConvert.transToUserInfo(userInfoDTO);
        // 插入
        userMapper.insert(userInfo);
        return BusinessResult.success(new BaseResponse());
    }


    /**
     * 判断是否为系统管理员
     *
     * @param userInfoDTO
     * @return
     */
    @Override
    public BusinessResult<IsAdminDTO> isSystemAdmin(UserInfoDTO userInfoDTO) {
        IsAdminDTO isAdminDTO = new IsAdminDTO();
        //todo 需要细化
        if (userInfoDTO.getAccount().equals(ADMIN_NAME)) {
            isAdminDTO.setIsAdmin(true);
            return BusinessResult.success(isAdminDTO);
        }
        isAdminDTO.setIsAdmin(false);
        return BusinessResult.success(isAdminDTO);
    }

    @Override
    public BusinessResult<UserInfoDTO> getUserInfo(Integer userId) {

        UserInfo userInfo = userMapper.select(userId);
        UserInfoDTO userInfoDTO = userConvert.transToUserInfoDTO(userInfo);
        return BusinessResult.success(userInfoDTO);
    }

    @Override
    public BusinessResult<PageResponse<UserInfoDTO>> getUserInfoByPage(UserPageQueryDTO userPageQueryDTO) {
        UserQueryBean userQueryBean = userConvert.trans(userPageQueryDTO);
        int count = userMapper.count(userQueryBean);
        if (count == 0) {
            return BusinessResult.success(PageResponse.nullValue(userPageQueryDTO.getPageQuery()));
        }
        List<UserInfo> userInfos = userMapper.selectByPage(userQueryBean, userPageQueryDTO.getPageQuery().limit(), userPageQueryDTO.getPageQuery().offset());
        List<UserInfoDTO> userInfoDTOS = new ArrayList<>();
        for (UserInfo userInfo : userInfos) {
            userInfoDTOS.add(userConvert.transToUserInfoDTO(userInfo));
        }
        PageResponse pageResponse = PageResponse.withValue(userPageQueryDTO.getPageQuery(), count, userInfoDTOS);
        return BusinessResult.success(pageResponse);
    }

    @Override
    public BusinessResult<Void> deleteUser(GetByIdRequest request) {
        userMapper.delete(request.getId());
        return BusinessResult.success(null);

    }

    @Override
    public BusinessResult<List<UserInfoDTO>> getUserInfoByOrgAccount(GetByAccountRequest request) {
        UserInfoDTO currentUser = getUserInfoByAuthCode(request).getBody();
        List<UserInfo>  userInfos = userMapper.selectByAccountAndOrgId(request.getAccount(), currentUser.getOrgId());
        if(CollectionUtils.isEmpty(userInfos)){
            return BusinessResult.success(Lists.newArrayList());
        }
        List<UserInfoDTO> userInfoDTOs=userInfos.stream().map(x->userConvert.transToUserInfoDTO(x)).collect(Collectors.toList());
        return BusinessResult.success(userInfoDTOs);

    }


}
